
package com.probiz.estoresa.system.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.common.model.system.Region;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.system.service.RegionManager;
import com.probiz.estore.webapp.util.RequestUtil;

public class RegionController extends GenericStoreAdminController<Region> {

	private RegionManager		regionManager;

	public void setRegionManager(RegionManager manager) {
		this.regionManager = manager;
	}

	@Override
	protected String getEntityName(Region entity) {
		return null;
	}


	@Override
	protected void initController() throws Exception {
		mgr = regionManager;
	}

	@Override
	protected void preSave(HttpServletRequest request, Region entity,
			BindException errors) {

	}

	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("system/regionList");
		Region rootRegion = regionManager.getDefaultRootRegion();
		Set<Region> regionSet = rootRegion.getChildren();
		List<Region> regionList = new ArrayList<Region>();
		regionList.addAll(regionSet);
		mv.addObject("rootRegion", rootRegion);
		mv.addObject("regionList", regionList);
		return mv;
	}

	/**
	 * 获取树节点，ajax方式
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView getTreeItems(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("/system/include/regionTreeAjax");
		String regionId = RequestUtil.getParameterNullSafe(request, "regionId");
		Region region = regionManager.getById(Integer.valueOf(regionId));
		Set<Region> regionSet = region.getChildren();
		List<Region> regionList = new ArrayList<Region>();
		regionList.addAll(regionSet);
		mv.addObject("regionList", regionList);
		return mv;

	}

	@Override
	public ModelAndView edit(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("system/regionForm");

		Integer regionId = RequestUtil.getInteger(request, "regionId");
		if (null != regionId) {
			// case:编辑
			Region region = regionManager.getById(regionId);
			mv.addObject("region", region);
		} else {
			// case:新增
			Integer parentRegionId = RequestUtil.getInteger(request,
					"parentRegionId");
			Region parentRegion = regionManager.getById(parentRegionId);
			mv.addObject("parentRegion", parentRegion);
			Region region = new Region();
			region.setParent(parentRegion);
			mv.addObject("region", region);
		}
		return mv;
	}

	/**
	 * 前置绑定，避免验证错误
	 * 
	 * @param entity
	 *            实体
	 */
	private void bindReady(Region entity) {
	}
	
	/**
	 * 加入返回参数
	 * 
	 * @param data
	 * @param product
	 * @param request
	 */
	private void buildReturnInfo(Map<String, Object> data,
			Region entity, HttpServletRequest request) {
		data.put("regionId", entity.getRegionId());
		data.put("regionName", entity.getRegionName());

	}
	
	public ModelAndView save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		// 取得Form对应的Model
		Region entity = formBackingObject(request);
		BindException errors = null;
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			bindReady(entity);
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 传给子类的实现，后者可以继续验证和加入错误到errors
			preSave(request, entity, errors);
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				regionManager.saveFully(entity);
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}

		buildReturnInfo(data, entity, request);

		return getModelAndAjaxJsonView(data);
	}
	
	/**
	 * 按categoryIds的顺序更新目录sortOrder
	 */
	public ModelAndView updateRegionsSortOrder(HttpServletRequest request,
			HttpServletResponse response) {
		Integer[] regionIds = RequestUtil.getIntegerArrayNullSafe(request,
				"regionIds");
		regionManager.updateRegionsSortOrder(regionIds);
		return null;
	}

	@Override
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer regionId = RequestUtil.getInteger(request, "regionId");
		Region region = regionManager.getById(regionId);
		Map<String, Object> data = regionManager.deleteFully(region);
		return getModelAndAjaxJsonView(data);

	}

}
